import { ref } from "vue";

export function useLength(showPicker, columns) {
  const onConfirm = ({ selectedValues, selectedOptions }) => {
    showPicker.value = false;
    const selectedValue = selectedValues[0];
    const selectedText = selectedOptions[0].text;
    if (columns.value.length === 3) {
      metricUnit.value = selectedValue;
      metricLabel.value = selectedText;
      metricToImperial();
      return;
    } 
      imperialUnit.value = selectedValue;
      imperialLabel.value = selectedText;
      imperialToMetric();
    
  };

  const metricLabel = ref("cm");
  const metric = ref();
  const metricUnit = ref(1);

  function metricToImperial() {
    // metric to centimeter than to inch
    const inchNum = Number(
      ((metric.value * metricUnit.value) / 2.54).toFixed(2)
    );
    imperial.value = Number((inchNum / imperialUnit.value).toFixed(2));
  }

  const imperialLabel = ref("in");
  const imperial = ref();
  const imperialUnit = ref(1);

  function imperialToMetric() {
    // imperial to inch than to centimeter
    const centimeterNum = Number(
      imperial.value * imperialUnit.value * 2.54
    ).toFixed(2);
    metric.value = Number((centimeterNum / metricUnit.value).toFixed(2));
  }

  return {
    metricLabel,
    metric,
    metricUnit,

    imperialLabel,
    imperial,
    imperialUnit,

    onConfirm,
    
    metricToImperial,
    imperialToMetric,

  };
}
